package anyThor

import (
	"encoding/json"
	"strconv"
)

func AnyToString(value interface{}) string {
	if value == nil {
		return ""
	}
	switch value.(type) {
	case float64: // 浮点型 3.0将会转换成字符串"3"
		ft, err := value.(float64)
		if !err {
			// logger
		}
		return strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		return strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		return strconv.Itoa(it)
	case uint:
		it := value.(uint)
		return strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		return strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		return strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		return strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		return strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		return strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		return strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		return strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		return strconv.FormatUint(it, 10)
	case string:
		return value.(string)
	case []byte:
		return string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		return string(newValue)
	}
}

func AnyToInt(t interface{}) int {
	var i int
	switch t.(type) {
	case uint:
		i = int(t.(uint))
		break
	case int8:
		i = int(t.(int8))
		break
	case uint8:
		i = int(t.(uint8))
		break
	case int16:
		i = int(t.(int16))
		break
	case uint16:
		i = int(t.(uint16))
		break
	case int32:
		i = int(t.(int32))
		break
	case uint32:
		i = int(t.(uint32))
		break
	case int64:
		i = int(t.(int64))
		break
	case uint64:
		i = int(t.(uint64))
		break
	case float32:
		i = int(t.(float32))
		break
	case float64:
		i = int(t.(float64))
		break
	case string:
		i, _ = strconv.Atoi(t.(string))
		if i == 0 && len(t.(string)) > 0 {
			f, _ := strconv.ParseFloat(t.(string), 64)
			i = int(f)
		}
		break
	case nil:
		i = 0
		break
	case json.Number:
		t3, _ := t.(json.Number).Int64()
		i = int(t3)
		break
	default:
		i = t.(int)
		break
	}
	return i
}
